//
//  HelloWorldScene.m
//  whattheword
//
//  Created by DRSAGITN on 7/18/14.
//  Copyright DRSAGITN 2014. All rights reserved.
//
// -----------------------------------------------------------------------

#import "HelloWorldScene.h"
#import "IntroScene.h"

// -----------------------------------------------------------------------
#pragma mark - HelloWorldScene
// -----------------------------------------------------------------------

@implementation HelloWorldScene
{
    CCSprite *_sprite;
    CCSprite *_highlight;
    CCSprite *helpBtn;
    NSMutableArray *GapObject_arr;
    NSMutableArray *LetObject_arr;
    NSMutableArray *preLetPosition_arr;
    NSString *answer;
    NSString *solution;
    NSString *given;
    
    int userPoints;
    CCLabelTTF *pointLabel;
    UIAlertView * HintAlert;
    //currentLevel
    //maxLevel
    //current diamond
    //current package id
    
    //solutionX
    //givenX
}

// -----------------------------------------------------------------------
#pragma mark - Create & Destroy
// -----------------------------------------------------------------------

+ (HelloWorldScene *)scene
{
    return [[self alloc] init];
}

// -----------------------------------------------------------------------

- (id)init
{
    // Apple recommend assigning self with supers return value
    self = [super init];
    if (!self) return(nil);
    
    // Enable touch handling on scene node
    self.userInteractionEnabled = YES;
    
    
    
    // Create a background 
    CCSprite *background = [CCSprite spriteWithImageNamed:@"background.png"];
    background.anchorPoint = CGPointMake(0, 0);
    [self addChild:background z:0];
    
    GapObject_arr = [NSMutableArray array];
    LetObject_arr = [NSMutableArray array];
    preLetPosition_arr = [NSMutableArray array];
    answer = @"";
    
    
    //HEADER
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    int currentUserLevel = [defaults integerForKey:@"user_level"];
    if(currentUserLevel == 0)
        currentUserLevel = 1;
    //level label
    CCLabelTTF *LevelLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d", currentUserLevel] fontName:@"Arial" fontSize:20.0f];
    LevelLabel.positionType = CCPositionTypeNormalized;
    LevelLabel.color = [CCColor whiteColor];
    LevelLabel.position = ccp(0.11f, 0.92f);
    [self addChild:LevelLabel];
    //user points
    userPoints = [defaults integerForKey:@"user_point"];
    if(userPoints == 0)
        userPoints = 100;
    pointLabel = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d points", userPoints] fontName:@"Arial" fontSize:15.0f];
    pointLabel.positionType = CCPositionTypeNormalized;
    pointLabel.color = [CCColor colorWithRed:162/255.0 green:175/255.0 blue:14/255.0];
    pointLabel.position = ccp(0.32f, 0.92f);
    [self addChild:pointLabel];
    
    //help button
    helpBtn = [CCSprite spriteWithImageNamed:@"help.png"];
    helpBtn.positionType = CCPositionTypeNormalized;
    helpBtn.position = ccp(0.8f, 0.92f);
    [self addChild:helpBtn];
    //fb button
    CCSprite *fbBtn = [CCSprite spriteWithImageNamed:@"fb.png"];
    fbBtn.positionType = CCPositionTypeNormalized;
    fbBtn.position = ccp(0.92f, 0.92f);
    [self addChild:fbBtn];
    
    //image
    CCSprite *theimage = [CCSprite spriteWithImageNamed:[NSString stringWithFormat:@"%d.jpg", currentUserLevel]];
    theimage.positionType = CCPositionTypeNormalized;
    theimage.position = ccp(0.5f, 0.68f);
    [self addChild:theimage];

    
    
    solution = @"YESWECAN";
    int slen = [solution length];
    int mlen = slen >= 9? 9: slen;
    for(int i = 0; i < slen; i++){
                answer = [NSString stringWithFormat:@"%@*", answer];
        CCSprite * gap = [CCSprite spriteWithImageNamed:@"blank.png"];
        //int f= gap.contentSize.width;

        gap.position = ccp((gap.contentSize.width+5)*(i%9)+ (self.contentSize.width/2 + gap.contentSize.width/2 - (mlen*gap.contentSize.width/2) - (mlen-1)/2*5), 36*(2-i/9)+139);
        gap.name = @"free";
        [self addChild:gap];
        [GapObject_arr addObject:gap];
        
    }
   
    _highlight = [CCSprite spriteWithImageNamed:@"blank_selected.png"];
    //_highlight.position = ccp((_highlight.contentSize.width/2), self.contentSize.height/2+20);
    CCSprite *gap1 = [GapObject_arr objectAtIndex:0];
    _highlight.position = gap1.position;
    
    _highlight.name = @"0";
    [self addChild:_highlight];
    
    given = @"EDYSWINRUECAIRTYAS";
    int len = [given length];
    int mmlen = len >= 9? 9: len;
    char buffer[len+1];
    
    [given getCharacters:buffer range:NSMakeRange(0, len)];
    for (int i = 0; i < len && i < 18; i++) {
        char current = buffer[2*i];
        
        CCSprite * letter = [CCSprite spriteWithImageNamed:[NSString stringWithFormat:@"%c.png", current] ];
        letter.position = ccp((letter.contentSize.width+5)*(i%9) +  (self.contentSize.width/2 + letter.contentSize.width/2 - (mmlen*letter.contentSize.width/2) - (mmlen-1)/2*5), 36*(2-i/9));
        
        [self addChild:letter];
        letter.name = [NSString stringWithFormat:@"%d", -1];
        [LetObject_arr addObject:letter];
        [preLetPosition_arr addObject:[NSValue valueWithCGPoint:letter.position]];
    }
    // done
	return self;
}

// -----------------------------------------------------------------------

- (void)dealloc
{
    // clean up code goes here
}

// -----------------------------------------------------------------------
#pragma mark - Enter & Exit
// -----------------------------------------------------------------------

- (void)onEnter
{
    // always call super onEnter first
    [super onEnter];
    
    // In pre-v3, touch enable and scheduleUpdate was called here
    // In v3, touch is enabled by setting userInteractionEnabled for the individual nodes
    // Per frame update is automatically enabled, if update is overridden
    
}

// -----------------------------------------------------------------------

- (void)onExit
{
    // always call super onExit last
    [super onExit];
}

// -----------------------------------------------------------------------
#pragma mark - Touch Handler
// -----------------------------------------------------------------------

-(void) touchBegan:(UITouch *)touch withEvent:(UIEvent *)event {
    CGPoint touchLoc = [touch locationInNode:self];
    
    //if touch on the letter, move the letter to the highlight or move back
    for (int i = 0; i< [LetObject_arr count]; i++) {
        CCSprite *sprite = [LetObject_arr objectAtIndex:i];
        if(CGRectContainsPoint([sprite boundingBox], touchLoc)){
            if([sprite.name intValue] >= 0){//move back
                answer = [answer stringByReplacingCharactersInRange:NSMakeRange([sprite.name intValue], 1) withString:@"*"];
                NSLog(answer);
                CGPoint prePoint = [[preLetPosition_arr objectAtIndex:i] CGPointValue];
                CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.3f position: prePoint];
                CCSprite *currentGap = [GapObject_arr objectAtIndex:[sprite.name intValue]];
                currentGap.name = @"free";
                sprite.name = [NSString stringWithFormat:@"%d", -1];
                [sprite runAction:actionMove];

            }
            else{
                answer = [answer stringByReplacingCharactersInRange:NSMakeRange([_highlight.name intValue], 1) withString:[given substringWithRange:NSMakeRange(i, 1)]];
                [self moveToHighLight:sprite];
                
//                NSLog(answer);
//                //move to high light
//                CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.3f position:_highlight.position];
//                sprite.name = [NSString stringWithFormat:@"%@", _highlight.name];
//                CCSprite * gap = [GapObject_arr objectAtIndex:[_highlight.name intValue]];
//                gap.name = @"occupied";
//                [sprite runAction:actionMove];
//                
//                //then move the high light to next position
//                int index = [_highlight.name intValue];
//                int isMoved = 0;
//                for(int j = index+1; j < [GapObject_arr count]; j++){
//                    CCSprite *nextGap = [GapObject_arr objectAtIndex:j];
//                    if([nextGap.name isEqualToString:@"free"]){
//                        CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.1f position:nextGap.position];
//                        _highlight.name = [NSString stringWithFormat:@"%d",j];
//                        isMoved = 1;
//                        [_highlight runAction:actionMove];
//                        break;
//                        
//                    }
//                }
//                if(isMoved == 0) {
//                    for (int j = 0; j < index +1; j++) {
//                        CCSprite *nextGap = [GapObject_arr objectAtIndex:j];
//                        if([nextGap.name isEqualToString:@"free"]){
//                            CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.1f position:nextGap.position];
//                            _highlight.name = [NSString stringWithFormat:@"%d",j];
//                            isMoved = 1;
//                            [_highlight runAction:actionMove];
//                            break;
//                            
//                        }
//                    }
//                }
//                if (isMoved == 0) {
//                    //dismiss highligh
//                    //[_highlight removeFromParent];
//                    //thong bao ket qua
//                    if([answer isEqualToString:solution]){
//                        CCLabelTTF *resultLabel = [CCLabelTTF labelWithString:@"Correct!!!" fontName:@"Arial" fontSize:15.0f];
//                        resultLabel.positionType = CCPositionTypeNormalized;
//                        resultLabel.color = [CCColor colorWithRed:20/255.0 green:107/255.0 blue:47/255.0];
//                        resultLabel.position = ccp(0.5f, 0.32f);
//                        [self addChild:resultLabel];
//
//                    }else{
//                        CCLabelTTF *resultLabel = [CCLabelTTF labelWithString:@"Try again!!!" fontName:@"Arial" fontSize:15.0f];
//                        resultLabel.positionType = CCPositionTypeNormalized;
//                        resultLabel.color = [CCColor redColor];
//                        resultLabel.position = ccp(0.5f, 0.32f);
//                        [self addChild:resultLabel];
//                    }
//                    
//                }
                

            }
            
        }
    }
    
        // if touch on the gap, move the highlight there
    for (int i = 0; i< [GapObject_arr count]; i++) {
        CCSprite *sprite = [GapObject_arr objectAtIndex:i];
        if(CGRectContainsPoint([sprite boundingBox], touchLoc)){
            CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.1f position:sprite.position];
            _highlight.name = [NSString stringWithFormat:@"%d",i];
            [_highlight runAction:actionMove];
            
        }

    }
    if(CGRectContainsPoint([helpBtn boundingBox], touchLoc)){
        if (userPoints >= 20) {
            HintAlert = [[UIAlertView alloc] initWithTitle:@"Reveal Box" message:@"Revealing a box will cost 20 points. Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [HintAlert show];
            });

        }
        else{
            HintAlert = [[UIAlertView alloc] initWithTitle:@"Not enough points" message:@"You don't have enough point to reveal." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                [HintAlert show];
            });
            
            
        }
        
    }
}

// -----------------------------------------------------------------------
#pragma mark - Button Callbacks
// -----------------------------------------------------------------------
- (void) alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        NSLog(@"User ok");
        userPoints -= 20;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setInteger: userPoints forKey:@"user_point"];
        [pointLabel setString:[NSString stringWithFormat:@"%d points", userPoints]];
        //reveal a box
        NSString * solutionLetter = [solution substringWithRange:NSMakeRange([_highlight.name intValue] , 1)];
        NSLog(solutionLetter);
        for (int i = 0; i < [given length]; i++) {
            CCSprite *objAtI = [LetObject_arr objectAtIndex:i];
            NSString *givenLetter = [given substringWithRange:NSMakeRange(i, 1)];
            NSLog(givenLetter);
            if([objAtI.name isEqualToString:@"-1"] && [solutionLetter isEqualToString:givenLetter]){
                answer = [answer stringByReplacingCharactersInRange:NSMakeRange([_highlight.name intValue], 1) withString:[given substringWithRange:NSMakeRange(i, 1)]];
                [self moveToHighLight:objAtI];

                break;
            }
        }
    }
    
}

- (void) moveToHighLight: (CCSprite*)sprite{
    
    //move to high light
    CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.3f position:_highlight.position];
    sprite.name = [NSString stringWithFormat:@"%@", _highlight.name];
    CCSprite * gap = [GapObject_arr objectAtIndex:[_highlight.name intValue]];
    gap.name = @"occupied";
    [sprite runAction:actionMove];
    
    //then move the high light to next position
    int index = [_highlight.name intValue];
    int isMoved = 0;
    for(int j = index+1; j < [GapObject_arr count]; j++){
        CCSprite *nextGap = [GapObject_arr objectAtIndex:j];
        if([nextGap.name isEqualToString:@"free"]){
            CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.1f position:nextGap.position];
            _highlight.name = [NSString stringWithFormat:@"%d",j];
            isMoved = 1;
            [_highlight runAction:actionMove];
            break;
            
        }
    }
    if(isMoved == 0) {
        for (int j = 0; j < index +1; j++) {
            CCSprite *nextGap = [GapObject_arr objectAtIndex:j];
            if([nextGap.name isEqualToString:@"free"]){
                CCActionMoveTo *actionMove = [CCActionMoveTo actionWithDuration:0.1f position:nextGap.position];
                _highlight.name = [NSString stringWithFormat:@"%d",j];
                isMoved = 1;
                [_highlight runAction:actionMove];
                break;
                
            }
        }
    }
    if (isMoved == 0) {
        //dismiss highligh
        //[_highlight removeFromParent];
        //thong bao ket qua
        if([answer isEqualToString:solution]){
            CCLabelTTF *resultLabel = [CCLabelTTF labelWithString:@"Correct!!!" fontName:@"Arial" fontSize:15.0f];
            resultLabel.positionType = CCPositionTypeNormalized;
            resultLabel.color = [CCColor colorWithRed:20/255.0 green:107/255.0 blue:47/255.0];
            resultLabel.position = ccp(0.5f, 0.32f);
            [self addChild:resultLabel];
            
        }else{
            CCLabelTTF *resultLabel = [CCLabelTTF labelWithString:@"Try again!!!" fontName:@"Arial" fontSize:15.0f];
            resultLabel.positionType = CCPositionTypeNormalized;
            resultLabel.color = [CCColor redColor];
            resultLabel.position = ccp(0.5f, 0.32f);
            [self addChild:resultLabel];
        }
        
    }


}

- (void)onBackClicked:(id)sender
{
    // back to intro scene with transition
    [[CCDirector sharedDirector] replaceScene:[IntroScene scene]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionRight duration:1.0f]];
}

// -----------------------------------------------------------------------
@end
